//
//  HWDispatchGroup.m
//  OCDemo
//
//  Created by 李含文 on 2021/5/6.
//

#import "HWDispatchGroup.h"

NSMutableArray *_HWDispatchGroup_array;

@interface HWDispatchGroup()
{
    dispatch_group_t group;
    dispatch_queue_t queue;
}

@end

typedef void (^hw_block)(HWDispatchGroup *group);

@implementation HWDispatchGroup

+ (HWDispatchGroup *)dispatchGroup {
    HWDispatchGroup *group = [[HWDispatchGroup alloc] init];
    return group;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        group = dispatch_group_create();
        queue = dispatch_get_global_queue(0, 0);
        if (!_HWDispatchGroup_array) _HWDispatchGroup_array = [NSMutableArray array];
        [_HWDispatchGroup_array addObject:self];
    }
    return self;
}

- (void)addAsyncTask:(void(^)(HWDispatchGroup *group))action {
    dispatch_group_enter(group);
    __weak typeof(self) weakSelf = self;
    dispatch_group_async(group, queue, ^{
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (action) action(strongSelf);
    });
}

- (void)taskComplete {
    dispatch_group_leave(group);
}

- (void)groupNotify:(void(^)(void))action {
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        if (action) action();
        if (!_HWDispatchGroup_array) _HWDispatchGroup_array = [NSMutableArray array];
        [_HWDispatchGroup_array removeObject:self];
    });
}

- (void)dealloc {
    NSLog(@"释放");
}
@end
